package com.loop.unclelend.ui.presenter

import com.loop.unclelend.network.ApiService
import com.loop.unclelend.network.ApiService.addCommonParams
import com.loop.unclelend.network.ApiService.addRandomParams
import com.loop.unclelend.network.IHttpCallback
import com.loop.unclelend.pro.ProPresenter
import com.loop.unclelend.ui.view.IView_Apply
import org.json.JSONObject

/**
 * UnncleLend
 * @Author wwdeng
 * @CreateTime: 2024/9/25 13:45
 * @Annotation：贷款申请 Presenter 实现
 */
class Pre_Apply(private val iView: IView_Apply): ProPresenter(iView) {

    /**
     * 获取贷款信息
     */
    fun requestApplyDataAction(){
        val params = JSONObject().addCommonParams().addRandomParams()
        params.put("path", ApiService.API_PATH.UNCLE_API_LOAN_APPLY_CUSTOM_LIMIT_PATH)
        params.put("amount",iView.getApplyAmount())
        val applyDays = iView.getApplyDays()
        if (applyDays.isNotEmpty()){
            params.put("days",applyDays)
        }
        val httpUrl = ApiService.getHttpUrl(ApiService.API_URL.UNCLE_API_COMMON_URL)
        doPostAction(httpUrl, params,object: IHttpCallback {
            override fun onRequestSuccess(data: JSONObject) {
                val obj = data.optJSONObject("obj")
                if (obj != null) {
                    //是否允许修改申请金额，不允许修改则不显示Seekbar
                    val chooseAmountFlag = obj.optBoolean("chooseAmountFlag",false)
                    when(chooseAmountFlag){
                        true -> {//允许选择贷款额度
                            iView.showOptionalViews(obj)
                        }
                        else -> {//不允许选择贷款额度
                            iView.showNotOptionalViews()
                        }
                    }

                    //设置贷款期限
                    iView.showLoanDurationList(obj)
                    //设置明细
                    iView.showLoadDetailsList(obj)
                }
            }

            override fun onRequestError(error: JSONObject) {
            }

            override fun onRequestFinish() {
                iView.hideUncleLoading()
            }
        })
    }

    /**
     * 创建贷款申请订单
     */
    fun requestCreateApplyOrderAction(){
        val params = JSONObject().addCommonParams().addRandomParams().apply {
            put("path", ApiService.API_PATH.UNCLE_API_LOAN_APPLY_ORDER_CREATE_PATH)
            put("amount",iView.getApplyAmount())
            put("days",iView.getApplyDays())
        }
        val httpUrl = ApiService.getHttpUrl(ApiService.API_URL.UNCLE_API_COMMON_URL)
        doPostAction(httpUrl,params,object : IHttpCallback{
            override fun onRequestSuccess(data: JSONObject) {
                iView.hideUncleLoading()
                iView.showLoanApplySuccess()
            }
            override fun onRequestError(error: JSONObject) {
            }
            override fun onRequestFinish() {
            }
        })
    }

}